﻿<?php

require_once(realpath(dirname(__FILE__)) . "/../../config.php");

class dbClass {

    var $showErrors = true;
    var $numQueries = 0;
    var $lastQuery;
    var $colInfo;
    var $queries;
    var $ready = false;

    function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
        $this->dbCon = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
        if (!$this->dbCon) {
            $this->showError("<h1>Có lỗi trong quá trình kết nối cơ sở dữ liệu</h1><p>Nguyên nhân có thể thông tin để kết nối bạn khai báo trong file <code>config.php</code> không đúng.</p><ul><li>Hãy kiểm tra thông tin username và password</li><li>Kiểm tra bạn đã khai báo đúng hostname?</li><li>Bạn có chắc database server đang chạy?</li></ul>");
            return;
        }
        
        $this->ready = true;
        $this->select($dbname);
    }

    function __destruct() {
        return true;
    }

    function select($db) {
        if (!@mysql_select_db($db, $this->dbCon)) {
            $this->ready = false;
            $this->showError("<h1>Không thể chọn database $db</h1><p>Chúng tôi có thể kết nối tới server nhưng không thể chọn database <code>$db</code>.</p><ul><li>Bạn có chắc database đó tồn tại?</li><li>Bạn hãy kiểm tra lại quyền truy xuất database của user <code>".DB_USER."</code> tới database <code>$db</code></li></ul>");
            return;
        }
    }

    function escape($string) {
        return addslashes( $string );
    }

    function escapeByRef(&$s) {
        $s = $this->escape($s);
    }

    function prepare($args = NULL) {
        if ( NULL === $args )
            return;
        $args = func_get_args();
        $query = array_shift($args);
        $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
        $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
        $query = str_replace('%s', "'%s'", $query); // quote the strings
        array_walk($args, array(&$this, 'escape_by_ref'));
        return $query;
    }
    
    function printError($str = '') {
        if (!$str) $str = mysql_error($this->dbCon);
        
        if ( !$this->showErrors )
            return false;
        
        $str = htmlspecialchars($str, ENT_QUOTES);
        $query = htmlspecialchars($this->lastQuery, ENT_QUOTES);
        
        print "<div class='Error'><p class='DbError'><strong>Now!chat database error:</strong> [$str]<br /><code>$query</code></p></div>";
    }

    function showErrors( $show = true ) {
        $errors = $this->showErrors;
        $this->showErrors = $show;
        return $errors;
    }

    function hide_errors() {
        $show = $this->showErrors;
        $this->showErrors = false;
        return $show;
    }

    function flush() {
        $this->lastResult = array();
        $this->colInfo = null;
        $this->lastQuery = null;
    }

    function query($query) {
        if ( !$this->ready )
            return false;
        
        
        $query = $this->prepare($query);
        
        // init result
        $return_val = 0;
        $this->flush();
        
        $this->lastQuery = $query;
        
        $this->result = @mysql_query($query, $this->dbCon);
        ++$this->numQueries;
        
        // If there is an error then take note of it..
        if ( $this->lastError = mysql_error($this->dbCon) ) {
            $this->printError();
            return false;
        }
        
        // insert, delete, update query
        if ( preg_match("/^\\s*(insert|delete|update|replace) /i", $query) ) {
            $this->rowsAffected = mysql_affected_rows($this->dbCon);
            if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
                $this->insert_id = mysql_insert_id($this->dbCon);
            }
            $return_val = $this->rowsAffected;
        } else {
            $i = 0;
            while ($i < @mysql_num_fields($this->result)) {
                $this->colInfo[$i] = @mysql_fetch_field($this->result);
                $i++;
            }
            $numRows = 0;
            while ( $row = @mysql_fetch_object($this->result) ) {
                $this->lastResult[$numRows] = $row;
                $numRows++;
            }
            
            @mysql_free_result($this->result);
            
            // Log number of rows the query returned
            $this->numRows = $numRows;
            
            // Return number of rows selected
            $return_val = $this->numRows;
        }
        
        return $return_val;
    }
    
    function add_magic_quotes( $array ) {
        foreach ( $array as $k => $v ) {
            if ( is_array( $v ) ) {
                $array[$k] = add_magic_quotes( $v );
            } else {
                $array[$k] = $this->escape( $v );
            }
        }
        return $array;
    }
    
    function insert($table, $data) {
        $data = $this->add_magic_quotes($data);
        foreach ( array_keys($data) as $k )
        {
            if(empty($data[$k]))
                $data[$k] = null;
        }
        
        $fields = array_keys($data);
        
        //echo "INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')";
        return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
    }

    function delete($table, $where){
        $wheres = array();
        
        if ( is_array( $where ) )
            foreach ( $where as $c => $v )
                $wheres[] = "$c = '" . $this->escape( $v ) . "'";
        else
            return false;
        
        return $this->query( "DELETE FROM $table WHERE " . implode( ' AND ', $wheres ));
    }
    
    function update($table, $data, $where){
        $data = $this->add_magic_quotes($data);
        $bits = $wheres = array();
        foreach ( array_keys($data) as $k )
        {
            if(empty($data[$k]))
                $bits[] = "`$k` = NULL";
            else
                $bits[] = "`$k` = '$data[$k]'";
        }
        
        if ( is_array( $where ) )
            foreach ( $where as $c => $v )
                $wheres[] = "$c = '" . $this->escape( $v ) . "'";
        else
            return false;
        
        return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
    }

    function getVar($query = null, $x = 0, $y = 0) {
        if ( $query )
            $this->query($query);
        
        if ( !empty( $this->lastResult[$y] ) ) {
            $values = array_values(get_object_vars($this->lastResult[$y]));
        }
        
        return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
    }

    function getRow($query = null, $y = 0) {
        if ( $query )
            $this->query($query);
        else
            return null;
        
        if ( !isset($this->lastResult[$y]) )
            return null;
        
        return $this->lastResult[$y] ? $this->lastResult[$y] : null;
    }

    function getCol($query = null , $x = 0) {
        if ( $query )
            $this->query($query);
        
        $new_array = array();
        
        for ( $i=0; $i < count($this->lastResult); $i++ ) {
            $new_array[$i] = $this->getVar(null, $x, $i);
        }
        
        return $new_array;
    }

    function getResults($query = null, $output = 'OBJECT') {
        if ( $query )
            $this->query($query);
        else
            return null;
        
        if ( $output == 'OBJECT' ) {
            return $this->lastResult;
        } elseif ( $output == 'OBJECT_K' ) {
            foreach ( $this->lastResult as $row ) {
                $key = array_shift( get_object_vars( $row ) );
                if ( !isset( $new_array[ $key ] ) )
                    $new_array[ $key ] = $row;
            }
            return $new_array;
        } elseif ( $output == 'ARRAY_A' || $output == 'ARRAY_N' ) {
            if ( $this->lastResult ) {
                $i = 0;
                foreach( $this->lastResult as $row ) {
                    if ( $output == 'ARRAY_N' ) {
                        $new_array[$i] = array_values( get_object_vars( $row ) );
                    } else {
                        $new_array[$i] = get_object_vars( $row );
                    }
                    ++$i;
                }
                return $new_array;
            }
        }
    }

    function getColInfo($info_type = 'name', $col_offset = -1) {
        if ( $this->colInfo ) {
            if ( $col_offset == -1 ) {
                $i = 0;
                foreach($this->colInfo as $col ) {
                    $new_array[$i] = $col->{$info_type};
                    $i++;
                }
                return $new_array;
            } else {
                return $this->colInfo[$col_offset]->{$info_type};
            }
        }
    }

    function showError($message) {
        if ( !$this->showErrors ) {
            $this->error = $message;
            return false;
        }
        die($message);
    }

    function getLastInsertID()
    {
        $result = @mysql_query("SELECT LAST_INSERT_ID()", $this->dbCon);
        
        if (!$result)
        { 
            return(false);
        } 
        else 
        {
            //echo 'ok';
            $output = @mysql_fetch_array($result);
            //var_dump($output);
            return($output[0]);
        }
    }
}

if ( !isset($db) )
    $db = new dbClass(DB_USER, DB_PASS, DB_NAME, DB_HOST);

?>
